import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './TableColumns'
import { TransportationOrderVO as ITableData } from './types'
import CustomTable from '@/components/QsfCustomTable'
import { searchConfig } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import './index.less'
import useCachePage from '@/hooks/useCachePage'
import {
  addAddressReq,
  cancelTransportationOrder,
  editTransportationOrder,
  getPageTransportationOrder,
  getSupplierAddressData,
  getTransportInfoReq,
  transportationOrderAppointment,
  transportationOrderCancel,
  updateBoxQty,
} from '@/api/logistics'
import { getRecentMonths } from '@/utils/util'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { message, Modal, Space, Spin, Tooltip } from 'antd'
import useModal from '@/hooks/useModal'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import { applicationTypeEnum, OperationLogType } from '@/constant'
import useViewLogs from '@/hooks/useViewLogs'
import { useAppSelector } from '@/store/hooks'
import { getSpuOptions } from '@/api/goods'
import TimeLineScroll from './components/TimeLineScroll'
import GenerateModal from '@/pages/Purchase/Delivery/components/GenerateModal'
import AddressModal from '@/pages/Purchase/Delivery/components/AddressModal'
import { SupplierTransportAddressVO } from '@/pages/Purchase/Delivery/types'
import dayjs from 'dayjs'
import LogsDrawer from '@/components/LogsDrawer'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [form] = useForm()
  const ProDevSeason = useGetProDevSeason()
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'transportationOrderCode',
    OperationLogType.TRANSPORT_ORDER,
  )
  const { setCachePage, getCachePage } = useCachePage()
  const defaultDateRange = getRecentMonths('YYYY-MM-DD HH:mm:ss')
  const [addressList, setaddressList] = useState<SupplierTransportAddressVO[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const TimeLineModalInstance = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const GenerateModalInstance = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const AddressModalInstance = useModal({
    onSuccess: () => {
      message.success('操作成功')
      AddressModalInstance?.form.resetFields()
      getAddressList()
    },
    autoClose: false,
  })
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getPageTransportationOrder, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      createTimeStart: defaultDateRange,
      transportStatusList: [0, 1],
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqestParams) => {
      const { ...reqParams } = reqestParams
      return {
        ...reqParams,
        createTimeStart:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[0] : null,
        createTimeEnd:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[1] : null,
        dispatchTimeStart:
          reqParams.dispatchTimeStart && reqParams.dispatchTimeStart.length === 2
            ? reqParams.dispatchTimeStart[0]
            : null,
        dispatchTimeEnd:
          reqParams.dispatchTimeStart && reqParams.dispatchTimeStart.length === 2
            ? reqParams.dispatchTimeStart[1]
            : null,
        deliveryTimeStart:
          reqParams.deliveryTimeStart && reqParams.deliveryTimeStart.length === 2
            ? reqParams.deliveryTimeStart[0]
            : null,
        deliveryTimeEnd:
          reqParams.deliveryTimeStart && reqParams.deliveryTimeStart.length === 2
            ? reqParams.deliveryTimeStart[1]
            : null,
      }
    },
  })
  useEffect(() => {
    handleCacheData()
  }, [])
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      const { SupplierOption, SpuOptions, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      setSpuOptions(SpuOptions || [])
      reload({ ...resetCacheData })
    }
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuId: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const getTransportInfo = async (info: ITableData) => {
    const res = await getTransportInfoReq({ id: info.id, wayBillNo: info.wayBillNo })
    if (res.code == 200) {
      TimeLineModalInstance.openModal({ ...info, timelineData: res?.data || [] })
    }
  }
  const onEdit = (info: ITableData) => {
    GenerateModalInstance.openModal({
      ...info,
      dataSource:
        info?.reserveInvoiceVOList?.map((item) => {
          return {
            ...item,
            supplierCode: info?.orderSupplierCode,
            supplierName: info?.orderSupplierName,
          }
        }) || [],
      dispatchTime: info?.dispatchTime ? dayjs(info.dispatchTime) : null,
      deliveryTime: info?.deliveryTime ? dayjs(info.deliveryTime) : null,
    })
  }
  useEffect(() => {
    if (GenerateModalInstance.currentRecord?.orderSupplierId) {
      getAddressList()
    }
  }, [GenerateModalInstance.currentRecord?.orderSupplierId])
  const onEditBoxQty = (info: ITableData) => {
    const instance = Modal.confirm({
      title: '提示',
      content: '确认要修改箱包数吗？',
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const expectBoxQty =
          info?.reserveInvoiceVOList?.reduce(
            (pre: number, current: any) => pre + (Number(current?.totalBoxQty) || 0),
            0,
          ) || 0
        const res = await updateBoxQty({ id: info.id, boxQty: expectBoxQty }).finally(() => instance.destroy())
        if (res.code == 200) {
          message.success('操作成功')
          reload()
        }
      },
    })
  }
  const changeStatus = async (info: ITableData, type: 1 | 2 | 3) => {
    const params = {
      id: info.id,
      wayBillNo: info.wayBillNo,
    }
    let res: any
    if (type == 1) {
      res = await transportationOrderAppointment(params)
    }
    if (type == 2) {
      res = await transportationOrderCancel(params)
    }
    if (type == 3) {
      res = await cancelTransportationOrder(params)
    }
    if (res.code == 200) {
      message.success('操作成功')
      reload()
    }
  }
  const getAddressList = async () => {
    const res = await getSupplierAddressData<SupplierTransportAddressVO>({
      supplierId: GenerateModalInstance.currentRecord?.orderSupplierId,
    })
    if (res?.code == 200) {
      const data = res?.data || []
      setaddressList(data)
    }
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  return (
    <PageContainer className="logistics_demand_wrap">
      <SearchForm
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfig({
          SupplierOption,
          handleSearchSupplier,
          ProDevSeason,
          SpuOptions,
          handleSearchSpuOptions,
          form,
        })}
        onFinish={async () => {
          setCachePage({
            ...form.getFieldsValue(),
            SupplierOption,
            SpuOptions,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          reset()
          setCachePage({
            current: 1,
            size: 10,
            createTimeStart: defaultDateRange,
            transportStatusList: [0, 1],
          })
        }}
      ></SearchForm>
      <CustomTable
        isAutoScrollY
        {...tableProps}
        columns={useIndexColumns({
          onEdit,
          onEditBoxQty,
          changeStatus,
          onViewLogs,
          getTransportInfo,
          FlashEditBoxQty: buttonCodeList.includes('FlashEditBoxQty'),
        })}
        rowKey={(rows) => rows?.id}
        tableRowGray={(record) => (record.transportStatus == 2 ? 'table-row-gray' : '')}
      ></CustomTable>
      <TimeLineScroll modalInstance={TimeLineModalInstance}></TimeLineScroll>
      <GenerateModal
        modalInstance={GenerateModalInstance}
        reqestFunction={editTransportationOrder}
        openModal={() => AddressModalInstance.openModal()}
        addressList={addressList}
      ></GenerateModal>
      <AddressModal
        modalInstance={AddressModalInstance}
        reqestFunction={addAddressReq}
        addressList={addressList}
        setaddressList={setaddressList}
        selectedRowInfos={GenerateModalInstance.currentRecord?.reserveInvoiceVOList || []}
        getAddressList={getAddressList}
      ></AddressModal>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
    </PageContainer>
  )
}

export default Index
